package com.winning.sx.microframework;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class BuildStaticFile {

    public void traverseFolder2(Map<String, File> result, String path, String type) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
//                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        traverseFolder2(result, file2.getAbsolutePath(), type);
                    } else {
                        if (file2.getName().toUpperCase().endsWith(type.toUpperCase())) {
                            System.out.println("文件:" + file2.getAbsolutePath());
                            result.put(file2.getAbsolutePath(), file2);
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }

    public void traverseFolder2(List result, String path, String type) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        traverseFolder2(result, file2.getAbsolutePath(), type);
                    } else {
                        if (file2.getName().toUpperCase().endsWith(type.toUpperCase())) {
                            System.out.println("文件:" + file2.getAbsolutePath());
                            result.add(file2.getAbsolutePath());
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }

    @Test
    public void Main() {
        /***
         * 1.把js文件，css文件的路径作为Map索引。updateTime作为value
         *
         * 2.找到html文件，读取里面的内容。 将script标签的src拿到，将link的src拿到
         * 3.找到src的updateTime，将全文的值进行替换
         */
        Map<String, File> jsMap = new HashMap<String, File>();
        traverseFolder2(jsMap, "D:\\12WorkSpace\\idea2017\\ERMS@Gitee\\src\\main\\resources\\assets", "js");
        Map<String, File> cssMap = new HashMap<String, File>();
        traverseFolder2(cssMap, "D:\\12WorkSpace\\idea2017\\ERMS@Gitee\\src\\main\\resources\\assets", "css");
        List htmlList = new ArrayList();
        traverseFolder2(htmlList, "D:\\12WorkSpace\\idea2017\\ERMS@Gitee\\src\\main\\resources\\views", ".ftl");
        String basePath = "D:\\12WorkSpace\\idea2017\\ERMS@Gitee\\src\\main\\resources";
        for (int i = 0; i < htmlList.size(); i++) {
            try {
                File input = new File(htmlList.get(i).toString());

                String str = "";
                try {
                    FileInputStream in = new FileInputStream(input);
                    // size 为字串的长度 ，这里一次性读完
                    int size = in.available();
                    byte[] buffer = new byte[size];
                    in.read(buffer);
                    in.close();
                    str = new String(buffer, "utf-8");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Document doc = Jsoup.parse(input, "utf-8");
                Elements scripts = doc.getElementsByTag("script");
                Elements links = doc.getElementsByTag("link");
                for (int j = 0; j < scripts.size(); j++) {
                    Element e = scripts.get(j);
                    String src = e.attr("src");
                    if ("".equals(src)) continue;
                    if (src.startsWith("http")) continue;
                    String old = e.attr("src");
                    Calendar cal = Calendar.getInstance();
                    if (src.indexOf("?") > 0) {
                        src = src.substring(0, src.indexOf("?"));
                    }
                    src = src.replace("${request.contextPath}", "");
                    src = (basePath + src).replaceAll("/", "\\\\");
                    try {
                        long time = jsMap.get(src.trim()).lastModified();
                        SimpleDateFormat format = new SimpleDateFormat("ssmmhhddMM");
                        src = src.substring(basePath.length()) + "?v=" + format.format(time);
                    } catch (Exception ex) {
                        System.out.println(input.getName() + "找不到：" + src);
                        return;
                    }
                    src = "${request.contextPath}" + src.replaceAll("\\\\", "/");
                    e.attr("src", src);
                    String newS = e.attr("src");;
                    old = old.replaceAll("\\{", "\\{");
//                    System.out.println(str);
                    str = str.replace(old, newS);
                }


                for (int j = 0; j < links.size(); j++) {
                    Element e = links.get(j);
                    String src = e.attr("href");
                    if ("".equals(src)) continue;
                    if (src.startsWith("http")) continue;
                    String old = e.attr("href");
                    Calendar cal = Calendar.getInstance();
                    if (src.indexOf("?") > 0) {
                        src = src.substring(0, src.indexOf("?"));
                    }
                    src = src.replace("${request.contextPath}", "");
                    src = (basePath + src).replaceAll("/", "\\\\");
                    try {
                        long time = cssMap.get(src.trim()).lastModified();
                        SimpleDateFormat format = new SimpleDateFormat("ssmmhhddMM");
                        src = src.substring(basePath.length()) + "?v=" + format.format(time);
                    } catch (Exception ex) {
                        System.out.println(input.getName() + "找不到：" + src);
                        return;
                    }
                    src = "${request.contextPath}" + src.replaceAll("\\\\", "/");
                    e.attr("href", src);
                    String newS =e.attr("href");
                    old = old.replaceAll("\\{", "\\{");
//                    System.out.println(str);
                    str = str.replace(old, newS);
                }

                input.delete();
                input.createNewFile();
                FileOutputStream fos = new FileOutputStream(htmlList.get(i).toString(), true);
                fos.write(str.getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void tt(String c, String a, String b) {
//        String a="<script type=\"text/javascript\" src=\"${request.contextPath}/assets/echarts/echarts.min.js\"></script>";
//        String c="aaa"+a+"bbb";
//        String b="<script type=\"text/javascript\" src=\"${request.contextPath}/assets/echarts/echarts.min.js?v=123\"></script>";
        a = a.replaceAll("\\{", "\\{");
        System.out.println(a);
        c = c.replace(a, b);
        System.out.println(c);
    }
}
